<template>
    <!-- 头部导航栏 -->
    <view class="post-header">
        <!-- 返回箭头 -->
        <view class="nav-left" @click="handleBack">
            <han-icon name="return" size="36" />
        </view>

        <text class="post-title">发帖</text>

        <text class="post-draft" @click="handleSaveDraft">保存为草稿</text>
    </view>
</template>

<script setup>
import { usePostStore } from '@/stores/postStores';
import { useUserStore } from '@/stores/userStores';

const postStore = usePostStore();
const userStore = useUserStore();

// 退出页面
const exitPage = () => {
    uni.navigateBack({
        delta: 1
    });

    postStore.clearForm();
};

let hasFormData = () => {
    return (
        postStore.formData.title ||
        postStore.formData.content ||
        postStore.mediaList.length > 0
    );
};

// 跳回上次一页
const handleBack = () => {
    if (hasFormData()) {
        uni.showModal({
            title: '提示',
            content: '确定要退出编辑吗？未保存的内容会消失！',
            confirmText: '保存并退出',
            cancelText: '直接退出',
            success: (res) => {
                if (res.confirm) {
                    handleSaveDraft().then(() => {
                        exitPage();
                    });
                } else if (res.cancel) {
                    exitPage();
                }
            }
        });
    } else {
        exitPage();
    }
};

// 处理保存草稿
const handleSaveDraft = async () => {
    if (!postStore.formData.title) {
        uni.showToast({
            title: '标题不能为空',
            icon: 'none'
        });

        return;
    }

    try {
        await postStore.saveDraft();
        // 确保数据加载完成后再退出
        await postStore.getPostsByUserId(userStore.currentUser.userId);
        exitPage();
    } catch (error) {
        console.error(error);
    }
};
</script>

<style lang="scss">
.post-header {
    display: flex;
    height: $han-nav-bar-height;
    align-items: center;
    justify-content: space-between;
    padding: 0 20rpx;
    box-sizing: border-box;
    border-bottom: 1rpx solid $han-global-border-color;

    .nav-left {
        width: 40rpx;
        height: 40rpx;
        line-height: 40rpx;
        text-align: center;
        border-radius: 50%;
    }

    .post-title {
        font-size: $han-font-size-xl;
        font-weight: bold;
    }

    .post-draft {
        width: 130rpx;
        text-align: right;
        font-size: $han-font-size-sm;
        transition: opacity 0.3s;

        &:active {
            opacity: 0.7;
        }
    }
}
</style>
